let that = null;
import store from "../../utils/factory";
import {
    addOrder,
    getSummary,
    payOrder,
    getAdressList,
    getVoucherList,
    getVoucherNum,
    getWallet
} from "../../utils/config";
import {
    accAdd
} from "../../utils/util"
Page({
    data: {
        detail: {},
        remark: "",
        address: null,
        productTotal: 0,
        orderId: "",
        total: 0,
        orderTotal: 0,
        express: 0,
        status: "",
        id: "",
        discountNum: 0,
        shopCarList: [],
        discount: null,
        haveExpress: true,
        usePonit: false,
        point: 0,
        balance: 0,
        ponitTotal: 0,
        expressThreshold: 0,
        addressType: "",
        addressNoExpress: true,
        expressText: ""
    },
    onLoad: function (e) {
        that = this;
    },
    onShow() {
        //地址
        let selectAddress = store.get("choiceAddress");
        console.log("selectAddress", selectAddress)
        let discount = store.get("discount");
        console.log("discount", discount)
        if (discount) {
            this.setData({
                discount: discount,
            })
            store.remove("discount");
        }
        if (selectAddress) {
            this.setData({
                address: selectAddress
            });
            store.remove("choiceAddress");
            that.initData()
        } else {
            this.getAdressList(function () {
                that.initData()
            });
        }
    },
    initData() {
        //订单信息
        let submitOrderDetail = store.get("submitOrderDetail") || {};
        console.log("submitOrderDetail", submitOrderDetail);
        let a = submitOrderDetail.shopCarList;
        console.log(a);
        if (a.length > 0) {
            a.map(item => {
                item.total = (item.marketPrice * item.quantity).toFixed(2);
            });
        }
        let total = 0;
        if (this.data.discount) {
            total = accAdd(submitOrderDetail.total, -this.data.discount.value)
            if (total < 0) {
                total = 0
            }
        } else {
            total = submitOrderDetail.total;
        }
        let haveExpress = true;
        let expressText = ""
        if (!submitOrderDetail.haveExpress) {
            haveExpress = false;
            expressText = `消费满${store.get("expressThreshold")}元包邮`
        } else {
            if (that.data.address && that.data.address.type == 3) {
                haveExpress = false;
                expressText = `自提点免运费`
            }
        }
        let discount = 0
        if (!!this.data.discount) {
            discount = this.data.discount.value
        }
        this.setData({
            // total: haveExpress ? (parseFloat(submitOrderDetail.total) + store.get("express") - discount).toFixed(2) : parseFloat(submitOrderDetail.total - discount).toFixed(2),
            orderTotal: submitOrderDetail.total,
            express: store.get("express"),
            haveExpress: haveExpress,
            productTotal: total,
            shopCarList: a,
            status: submitOrderDetail.status || "",
            id: submitOrderDetail.id || "",
            expressText: expressText,
            expressThreshold: store.get("expressThreshold")
        });
        this.getToalNum()
        this.getVoucherNum();
        this.getWallet();
    },
    watchRemark(e) {
        this.setData({
            remark: e.detail.value
        });
    },
    getWallet() {
        getWallet().then(res => {
            this.setData({
                point: res.data.point,
                balance: res.data.wallet
            })
        })
    },
    getAdressList(fn) {
        getAdressList().then(res => {
            if (res.rows.length > 0) {
                res.rows.map(item => {
                    if (item.defaultFlag == true) {
                        that.setData({
                            address: item
                        });
                    }
                });
            }
            fn && fn()
        });
    },
    addAddress() {
        wx.navigateTo({
            url: "../addressHandle/addressHandle?type=add"
        });
    },
    switch1Change(e) {
        this.setData({
            usePonit: e.detail.value
        })
        if (e.detail.value) {
            let total = this.data.total - this.data.point / 100;
            let pointTotal = this.data.total - this.data.point / 100
            if (total < 0) {
                total = 0
            }
            this.setData({
                total: Math.floor(total * 100) / 100,
                pointTotal: pointTotal
            })
        } else {
            let total = this.data.pointTotal + this.data.point / 100;
            this.setData({
                total: Math.floor(total * 100) / 100,
                pointTotal: total
            })
        }
    },
    getVoucherNum() {
        getVoucherNum({
            total: parseInt(this.data.orderTotal)
        }).then(res => {
            this.setData({
                discountNum: Number(res.total)
            })
        })
    },
    goDiscount() {
        console.log(this.data.orderTotal)
        if (this.data.discountNum == 0) {
            return false
        }
        wx.navigateTo({
            url: `../discount/discount?type=choice&total=${this.data.orderTotal}`
        });
    },
    updateAddress() {
        wx.navigateTo({
            url: "../addressList/addressList?type=choice"
        });
    },
    pay() {
        wx.showLoading({
            title: "加载中..."
        })
        this.payOrder(this.data.id);
    },
    payOrder(id) {
        payOrder({
            id: id
        }).then(res => {
            wx.hideLoading();
            this.payWX(res.data);
        });
    },
    payWX(data) {
        wx.requestPayment({
            timeStamp: data.timeStamp,
            nonceStr: data.nonceStr,
            package: data.packageValue,
            signType: "MD5",
            paySign: data.paySign,
            success: function (res) {
                wx.redirectTo({
                    url: `../resultPage/resultPage`
                });
            },
            fail: function (res) {
                wx.redirectTo({
                    url: `../orderDetail/orderDetail?id=${that.data.orderId||that.data.id}`
                });
            },
            complete: function (res) {}
        });
    },
    getToalNum() {
        let items = [];
        that.data.shopCarList.map(item => {
            items.push({
                category: item.id,
                quantity: item.quantity
            });
        });
        getSummary({
                address: that.data.address ? that.data.address.id : "",
                items: items,
                remark: that.data.remark,
                voucher: that.data.discount ? that.data.discount.id : "",
                point: that.data.usePonit ? that.data.point : 0
            })
            .then(({
                data
            }) => {
                that.setData({
                    total: data
                })
            })
            .catch(err => {
                wx.hideLoading();
            });
    },
    addOrder: function (e) {
        if (!this.data.address) {
            wx.showModal({
                title: "温馨提示",
                content: "请先填写收货地址",
                showCancel: false, //是否显示取消按钮
                success: function (res) {}
            });
            return false
        }
        let tmplIds = ['RfWOLZ-pRC9mO_R7QyeG63GC8giQRKzUeBwHjIUhrps']
        wx.requestSubscribeMessage({
            tmplIds: tmplIds,
            success(res) {
                // if (!res['RfWOLZ-pRC9mO_R7QyeG63GC8giQRKzUeBwHjIUhrps'].includes('accept')) {
                //     return false
                // }
                let items = [];
                wx.showLoading({
                    title: "订单生成中..."
                });
                that.data.shopCarList.map(item => {
                    items.push({
                        category: item.id,
                        quantity: item.quantity
                    });
                });
                addOrder({
                        address: that.data.address.id,
                        items: items,
                        remark: that.data.remark,
                        voucher: that.data.discount ? that.data.discount.id : "",
                        point: that.data.usePonit ? that.data.point : 0
                    })
                    .then(res => {
                        that.setData({
                            orderId: res.data.id
                        })
                        that.payOrder(res.data.id);
                    })
                    .catch(err => {
                        wx.hideLoading();
                    });
            }
        })
    }
});